package com.yxy.common;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.validation.Errors;
import org.springframework.validation.ObjectError;
import java.lang.reflect.InvocationTargetException;

/**
 * Restful Base 提供了很多工具
 * Created by brucezhang on 12/01/2017.
 */
public class BaseController<T> {

    private static Logger logger = LoggerFactory.getLogger(BaseController.class);


    /**
     * 生成 Result INfo 根据 resultCode 和 message 并赋值给 resultInfo
     *
     * @param resultCode 返回状态码
     * @param message    返回消息
     * @return
     */
    private ResponseInfo<Object> buildResponseInfo(Integer resultCode, String message, Object data, String error) {
        ResponseInfo<Object> resultInfo = new ResponseInfo<Object>();
        resultInfo.setCode(resultCode);
        resultInfo.setMessage(message);
        resultInfo.setData(data);
        resultInfo.setError(error);
        return resultInfo;
    }

    protected ResponseInfo buildResponseInfo(Integer resultCode, String message) {
        return buildResponseInfo(resultCode, message, null, null);
    }

    protected ResponseInfo buildResponseInfo(Integer resultCode, String message, T data) {
        return buildResponseInfo(resultCode, message, data, null);
    }

    /**
     * @return
     */
    protected ResponseInfo<T> buildSuccessResponseInfo() {
        return new ResponseInfo().success();
    }

    /**
     * 生成 HTTP 状态码为 200 ，封装了 resultCode 和 提示信息的 ResponseInfo
     * <p>
     * 封装好 返回 的 SUCCESS code，也返回消息
     *
     * @param data 成功并携带 结果集合
     * @return ResponseInfo
     */
    protected ResponseInfo<T> buildSuccessResponseInfo(T data) {
        return new ResponseInfo().success(data);
    }

    protected ResponseInfo<Object> buildErrorResponseInfo(Integer errorCode, String errMessage) {
        return new ResponseInfo().error(errorCode, errMessage);
    }

    /**
     * 从Errors中取出参数错误，返回包含信息的ResponseInfo
     *
     * @param errors  验证的错误信息对象
     * @param message 外加错误信息
     * @return ResponseInfo
     */
    protected ResponseInfo buildInputErrors(Errors errors, String message) {
        StringBuffer errorInfo = new StringBuffer();
        for (ObjectError error : errors.getAllErrors()) {
            errorInfo.append(error.getDefaultMessage()).append("\n");
        }
        return buildErrorResponseInfo(ResultCodes.USER_PARAMETER_WRONG, message + " ：" + errorInfo);
    }

    protected Object contentCopy(Object source) throws InvocationTargetException, IllegalAccessException {
        Object dest = new Object();
        BeanUtils.copyProperties(dest, source);
        return dest;
    }




}
